const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
// 创建一个SMTP客户端配置
var config = {
  host: 'smtp.163.com', //网易163邮箱 smtp.163.com，QQ邮箱就别动smtp.qq.com
  port: 25, //网易邮箱端口 25，QQ邮箱就465
  auth: {
    user: 'carlson_shi@163.com', //邮箱账号
    pass: 'RLUHUEKNKHFIURID' //邮箱的授权码
  }
};
const xcxname = '科大实践教学过程管理系统'; //你的小程序名称

/*
下
面
不
用
管
*/

//引入发送邮件的类库
const nodemailer = require('nodemailer')

var transporter = nodemailer.createTransport(config);
// 云函数入口函数
exports.main = async (event, context) => {
  console.log('定时器触发了吗');
  console.log('event', event);
  Timing()

  function Timing() {
    db.collection('course-email').orderBy('TimeTS', 'asc').get().then(res => {
      // 获取返回来的数组数据
      var list = res.data;
      console.log('list', list);
      if (list.length == 0) {
        console.log('数据库已经没有数据了');
        return false;
      }
      // 这是三十分钟
      var hour = 1800000;
      // 这是时间戳
      var time = Date.now();
      list.forEach((item, index) => {
        console.log('item', item);
        if (item.addTime - time < hour) {
          console.log('成员', item.courseMember);
          var emails = item.courseMember.map(item => item.email);
          console.log('emails', emails);
          var nickName = item.courseMember.map(item => item.nickName);
          console.log('nickName', nickName);
          console.log('coursename', item.coursename);
          console.log('删除第', index + '条数据，删除id是' + item._id);
          var doc = {
            type: 1,
            nickName: nickName,
            emails: emails,
            coursename: item.coursename
          };
          sendList(doc)
          let id = item._id
          console.log('删除id', id);
          db.collection('course-email').where({
            _id: id
          }).remove({
            success: function (res) {

              console.log(res, '删除成功');
            }
          })

        }
      });
      Promise.all(list)
        .then(data => {
          console.log('成功');

        })
        .catch(e => {

          console.log(e);
        });
    })

    function sendList(doc) {
      console.log('doc', doc);
      switch (doc.type) {
        case 1:
          var sub = '上课提醒';
          var con = '<div>亲爱的同学，你好！<br><br>你在【<font color="#ff0000">' + xcxname + '</font>】小程序内参与的《<strong>' + doc.coursename + '</strong>》课程还有半个小时就要上课了<br><br>请登录小程序提前做好准备</div>'
          break;
        default:
          var sub = '上课提醒';
          var con = '<div>亲爱的《<strong>' + doc.nickName + '</strong>》同学，你好！<br><br>你在【<font color="#ff0000">' + xcxname + '</font>】小程序内参与的《<strong>' + doc.coursename + '</strong>》课还有半个小时就上课了<br><br>请提前做好准备</div>'
          break;
      }

      var mail = {
        from: '来自' + xcxname + ' <' + config.auth.user + '>',
        subject: sub,
        to: doc.emails,
        html: con
      };
      var res = transporter.sendMail(mail);
      return res;
    }



  }



}